<script setup lang="ts">
import type { VisitorApi } from '#/api/core';

import { computed, onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

import { message } from 'ant-design-vue';

import { getTalentDetailApi, updateTalentFavoriteApi } from '#/api/core';

type StatusType = 'assigned' | 'completed' | 'default' | 'idle' | 'testing';

interface VisitorInfo {
  id: string;
  name: string;
  age?: number | string;
  profession: string;
  city: string;
  cityFull?: string;
  expertise: string[];
  skills: string[];
  experience: string;
  isCollected: boolean;
  statusType: StatusType;
  statusLabel: string;
  avatar?: string;
  summary?: string;
  description?: string;
  personalDetails?: string;
  phone?: string;
  email?: string;
  birthDate?: string;
  attachments: Array<{ name: string; url: string }>;
  gender?: string;
}

defineOptions({ name: 'VisitorDetail' });

const route = useRoute();
const router = useRouter();
const visitor = ref<null | VisitorInfo>(null);
const loading = ref(false);
const collecting = ref(false);
const isPublicView = computed(
  () => route.meta?.isPublicVisitor === true || route.query.share === '1',
);

const statusStyleMap: Record<StatusType, { class: string }> = {
  idle: { class: 'bg-green-100 text-green-800' },
  testing: { class: 'bg-blue-100 text-blue-800' },
  assigned: { class: 'bg-orange-100 text-orange-800' },
  completed: { class: 'bg-gray-100 text-gray-800' },
  default: { class: 'bg-gray-100 text-gray-700' },
};

function resolveStatusType(status?: string): StatusType {
  if (!status) {
    return 'default';
  }
  const normalized = status.toLowerCase();
  if (['available', 'idle', '待命'].includes(normalized)) {
    return 'idle';
  }
  if (['testing', '测试中', '试用'].includes(normalized)) {
    return 'testing';
  }
  if (['assigned', 'external', '外派', '外派中'].includes(normalized)) {
    return 'assigned';
  }
  if (['completed', 'finished', '完成'].includes(normalized)) {
    return 'completed';
  }
  return 'default';
}

function normalizeTagField(value?: null | string) {
  if (!value) {
    return [] as string[];
  }
  return value
    .split(/[,，]/)
    .map((item) => item.trim())
    .filter(Boolean);
}

function mapExperienceYears(years?: number) {
  if (!years && years !== 0) {
    return '—';
  }
  return years > 0 ? `${years}年经验` : '应届/无经验';
}

function parseAttachments(attachs?: null | string) {
  if (!attachs) {
    return [] as Array<{ name: string; url: string }>;
  }
  return attachs
    .split(',')
    .map((item) => item.trim())
    .filter(Boolean)
    .map((url) => {
      const segments = url.split('/');
      const name = segments[segments.length - 1] || url;
      return {
        name,
        url,
      };
    });
}

function transformDetail(detail: VisitorApi.TalentDetail): VisitorInfo {
  const expertise = normalizeTagField(
    detail.expertiseFieldText ||
      detail.expertiseField_dictText ||
      detail.expertiseField,
  );
  const skills = normalizeTagField(
    detail.skillTagsText || detail.skillTags_dictText || detail.skillTags,
  );
  const statusType = resolveStatusType(detail.status);

  return {
    id: detail.id,
    name: detail.realName || detail.createBy || '未命名',
    age: detail.age ?? '—',
    profession:
      detail.professionText ||
      detail.profession_dictText ||
      detail.profession ||
      '未填写职业',
    city:
      detail.cityText || detail.city_dictText || detail.city || '未填写地区',
    cityFull: detail.cityText,
    expertise,
    skills,
    experience: mapExperienceYears(detail.experienceYears),
    isCollected: detail.collected === 1,
    statusType,
    statusLabel:
      detail.statusText ||
      detail.status_dictText ||
      detail.statusType ||
      detail.status ||
      '未知状态',
    avatar: detail.avator,
    summary: detail.summary,
    description: detail.summary || '',
    personalDetails: detail.personalDetails,
    phone: detail.phone,
    email: detail.email,
    birthDate: detail.birthDate,
    attachments: parseAttachments(detail.attachs),
    gender: detail.sexText || detail.sex_dictText || detail.sex || '—',
  };
}

async function fetchVisitorDetail() {
  loading.value = true;
  try {
    const visitorId = route.params.id as string | undefined;
    if (!visitorId) {
      throw new Error('缺少游人ID');
    }
    const detail = await getTalentDetailApi(visitorId);
    visitor.value = transformDetail(detail);
  } catch (error) {
    console.error('获取游人详情失败:', error);
    message.error('获取游人详情失败，请稍后重试');
  } finally {
    loading.value = false;
  }
}

async function toggleCollect() {
  if (!visitor.value || collecting.value) {
    return;
  }
  if (isPublicView.value) {
    message.info('请登录后使用收藏功能');
    return;
  }
  collecting.value = true;
  try {
    const nextStatus = visitor.value.isCollected ? 0 : 1;
    await updateTalentFavoriteApi({
      talentId: visitor.value.id,
      isFavorite: nextStatus,
    });
    visitor.value.isCollected = nextStatus === 1;
    message.success(nextStatus === 1 ? '收藏成功' : '已取消收藏');
  } catch (error) {
    console.error('更新收藏状态失败:', error);
    message.error('更新收藏状态失败，请稍后重试');
  } finally {
    collecting.value = false;
  }
}

function handleShare() {
  if (!visitor.value) {
    return;
  }
  const shareUrl = new URL(
    `/#/visitor-share/${visitor.value.id}`,
    window.location.origin,
  );
  window.open(shareUrl.toString(), '_blank', 'noopener');
  message.success('已在新标签页打开分享页面');
}

function downloadAttachment() {
  message.info('下载功能开发中，敬请期待');
}

function goBack() {
  router.go(-1);
}

onMounted(() => {
  fetchVisitorDetail();
});
</script>

<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 加载状态 -->
    <div v-if="loading" class="flex h-64 items-center justify-center">
      <div
        class="h-8 w-8 animate-spin rounded-full border-b-2 border-amber-500"
      ></div>
    </div>

    <!-- 游人详情内容 -->
    <div v-else-if="visitor" class="mx-auto max-w-4xl p-6">
      <!-- 顶部操作按钮 -->
      <div v-if="!isPublicView" class="mb-6 flex justify-end space-x-4">
        <button
          class="rounded-md px-4 py-2 text-sm font-medium transition-colors"
          :class="[
            visitor.isCollected
              ? 'bg-yellow-500 text-white hover:bg-yellow-600'
              : 'bg-gray-100 text-gray-700 hover:bg-gray-200',
          ]"
          @click="toggleCollect"
        >
          {{ visitor.isCollected ? '已收藏' : '未收藏' }}
        </button>
        <button
          class="flex items-center space-x-2 rounded-md bg-gray-100 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-200"
          @click="handleShare"
        >
          <svg
            class="h-4 w-4"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.367 2.684 3 3 0 00-5.367-2.684z"
            />
          </svg>
          <span>分享</span>
        </button>
      </div>

      <!-- 游人信息 -->
      <div
        class="mb-6 rounded-lg border border-gray-200 bg-white p-6 shadow-sm"
      >
        <div class="flex items-start space-x-6">
          <!-- 头像 -->
          <div
            class="flex h-24 w-24 items-center justify-center overflow-hidden rounded-full border-4 border-purple-200 bg-gradient-to-r from-blue-400 to-purple-500 text-2xl font-bold text-white"
          >
            <img
              v-if="visitor.avatar"
              :src="visitor.avatar"
              alt="头像"
              class="h-full w-full object-cover"
            />
            <span v-else>{{ visitor.name.charAt(0) }}</span>
          </div>

          <!-- 基本信息 -->
          <div class="flex-1">
            <div class="mb-4 flex items-center space-x-4">
              <h1 class="text-2xl font-bold text-gray-900">
                {{ visitor.name }}
              </h1>
              <span
                class="rounded-full px-3 py-1 text-sm font-medium"
                :class="statusStyleMap[visitor.statusType].class"
              >
                {{ visitor.statusLabel }}
              </span>
            </div>

            <!-- 下载附件按钮 -->
            <button
              class="mb-4 flex items-center space-x-2 rounded-md bg-gray-100 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-200"
              @click="downloadAttachment"
            >
              <svg
                class="h-4 w-4"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"
                  d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
                />
              </svg>
              <span>下载附件</span>
            </button>

            <!-- 详细信息网格 -->
            <div class="grid grid-cols-2 gap-6">
              <div class="space-y-4">
                <div class="space-y-1">
                  <label class="text-sm font-medium text-gray-500">游人职业</label>
                  <p class="text-lg text-gray-900">{{ visitor.profession }}</p>
                </div>
                <div class="space-y-1">
                  <label class="text-sm font-medium text-gray-500">性别</label>
                  <p class="text-lg text-gray-900">{{ visitor.gender }}</p>
                </div>
                <div class="space-y-1">
                  <label class="text-sm font-medium text-gray-500">年龄</label>
                  <p class="text-lg text-gray-900">{{ visitor.age ?? '—' }}</p>
                </div>
              </div>
              <div class="space-y-4">
                <div class="space-y-1">
                  <label class="text-sm font-medium text-gray-500">从业时间</label>
                  <p class="text-lg text-gray-900">{{ visitor.experience }}</p>
                </div>
                <div class="space-y-1">
                  <label class="text-sm font-medium text-gray-500">所在地区</label>
                  <p class="text-lg text-gray-900">
                    {{ visitor.cityFull || visitor.city }}
                  </p>
                </div>
                <div v-if="visitor.birthDate" class="space-y-1">
                  <label class="text-sm font-medium text-gray-500">出生日期</label>
                  <p class="text-lg text-gray-900">{{ visitor.birthDate }}</p>
                </div>
              </div>
            </div>

            <div class="mt-6 grid gap-4 md:grid-cols-2">
              <div class="space-y-1">
                <label class="text-sm font-medium text-gray-500">手机号</label>
                <p class="text-lg text-gray-900">
                  {{ visitor.phone || '—' }}
                </p>
              </div>
              <div class="space-y-1">
                <label class="text-sm font-medium text-gray-500">邮箱</label>
                <p class="text-lg text-gray-900">
                  {{ visitor.email || '—' }}
                </p>
              </div>
            </div>

            <!-- 擅长领域 -->
            <div class="mt-6">
              <label class="mb-2 block text-sm font-medium text-gray-500">擅长领域</label>
              <div class="flex flex-wrap gap-2">
                <span
                  v-for="(expertise, index) in visitor.expertise"
                  :key="index"
                  class="rounded-full bg-blue-100 px-3 py-1 text-sm font-medium text-blue-800"
                >
                  {{ expertise }}
                </span>
              </div>
            </div>

            <!-- 技能标签 -->
            <div class="mt-4">
              <label class="mb-2 block text-sm font-medium text-gray-500">技能标签</label>
              <div class="flex flex-wrap gap-2">
                <span
                  v-for="(skill, index) in visitor.skills"
                  :key="index"
                  class="rounded-full bg-green-100 px-3 py-1 text-sm font-medium text-green-800"
                >
                  {{ skill }}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 游人概述 -->
      <div
        class="mb-6 rounded-lg border border-gray-200 bg-white p-6 shadow-sm"
      >
        <h2 class="mb-4 text-lg font-semibold text-gray-900">游人概述</h2>
        <p class="leading-relaxed text-gray-700">
          {{ visitor.summary || visitor.description || '暂无概述信息' }}
        </p>
      </div>

      <!-- 详细资料 -->
      <div
        class="mb-6 rounded-lg border border-gray-200 bg-white p-6 shadow-sm"
      >
        <h2 class="mb-4 text-lg font-semibold text-gray-900">详细资料</h2>
        <div
          v-if="visitor.personalDetails"
          class="prose prose-sm max-w-none text-gray-700"
          v-html="visitor.personalDetails"
        ></div>
        <div v-else class="py-8 text-center text-gray-500">
          <svg
            class="mx-auto h-12 w-12 text-gray-400"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
            />
          </svg>
          <p class="mt-2 text-sm text-gray-500">暂无详细资料</p>
        </div>
      </div>

      <!-- 附件列表 -->
      <div
        v-if="visitor.attachments.length > 0"
        class="mb-6 rounded-lg border border-gray-200 bg-white p-6 shadow-sm"
      >
        <h2 class="mb-4 text-lg font-semibold text-gray-900">附件资料</h2>
        <ul class="space-y-3">
          <li
            v-for="file in visitor.attachments"
            :key="file.url"
            class="flex items-center justify-between rounded-lg border border-gray-100 bg-gray-50 px-4 py-3 text-sm text-gray-700 transition-colors hover:border-amber-400 hover:bg-white"
          >
            <span class="truncate pr-4">{{ file.name }}</span>
            <a
              :href="file.url"
              target="_blank"
              rel="noopener noreferrer"
              class="text-amber-600 hover:text-amber-500"
            >
              下载
            </a>
          </li>
        </ul>
      </div>

      <!-- 返回按钮 -->
      <div class="mt-6 flex justify-end">
        <button
          class="flex h-12 w-12 items-center justify-center rounded-full bg-gray-100 text-gray-700 transition-colors hover:bg-gray-200"
          @click="goBack"
        >
          <svg
            class="h-6 w-6"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="M11 19l-7-7 7-7m8 14l-7-7 7-7"
            />
          </svg>
        </button>
      </div>
    </div>

    <!-- 未找到数据 -->
    <div v-else class="flex h-64 items-center justify-center">
      <div class="text-center">
        <svg
          class="mx-auto h-12 w-12 text-gray-400"
          fill="none"
          stroke="currentColor"
          viewBox="0 0 24 24"
        >
          <path
            stroke-linecap="round"
            stroke-linejoin="round"
            stroke-width="2"
            d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z"
          />
        </svg>
        <h3 class="mt-2 text-sm font-medium text-gray-900">未找到游人信息</h3>
        <p class="mt-1 text-sm text-gray-500">请检查链接是否正确</p>
      </div>
    </div>
  </div>
</template>
